package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.SearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import com.atguigu.gulimall.search.vo.SearchReult;
import com.atguigu.gulimall.search.vo.v1.MallGoodsDto;
import com.atguigu.gulimall.search.vo.v1.SearchByWeightParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guoch0613@163.com
 * @Description
 * @create 2021-04-03 16:06
 */
@Slf4j
@Service("SearchService")
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchReult searchSortByWeight(SearchByWeightParam searchParam) {
        log.info(">>>>>>>>>>>>>>es查询开始<<<<<<<<<<<<<<<");
        SearchReult searchReult = new SearchReult();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (searchParam.getIslist() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("is_marketable", searchParam.getIsmarketable()));
        }
        if (searchParam.getIsmarketable() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("is_list", searchParam.getIslist()));
        }

        sourceBuilder.query(boolQueryBuilder);
        //指定goods_weight，传入排序方式
        if (!StringUtils.isEmpty(searchParam.getOrder())) {
            SortOrder order = searchParam.getOrder().equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort("goods_weight", order);
        }
        //3 分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * searchParam.getPageSize());
        sourceBuilder.size(searchParam.getPageSize());
        log.info(">>>>>>>>>>>构建的DSL语句----{}<<<<<<<<<<<<<<<<", sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.T_MALL_GOODS_INDEX}, sourceBuilder);
        try {
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            //1. 封装查询到的商品信息
            SearchHits hits = response.getHits();
            if (hits != null && hits.getHits().length > 0) {
                List<MallGoodsDto> mallGoodsDtos = new ArrayList<>();
                for (SearchHit hit : hits) {
                    MallGoodsDto mallGoodsDto = JSON.parseObject(hit.getSourceAsString(), MallGoodsDto.class);
                    mallGoodsDtos.add(mallGoodsDto);
                }
                searchReult.setGoods(mallGoodsDtos);
            }
            //当前页码
            searchReult.setPageNum(searchParam.getPageNum());
            //总页数
            long total = hits.getTotalHits().value;
            searchReult.setTotal(total);
            Integer totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                    (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total / EsConstant.PRODUCT_PAGESIZE + 1;
            searchReult.setTotalPages(totalPages);
            log.info(">>>>>>>>>>>>>>es查询成功<<<<<<<<<<<<<<<");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchReult;
    }

    @Override
    public SearchResult getSearchResult(SearchParam searchParam) {
        SearchResult result = null;
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        try {
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        //1. 封装查询到的商品信息
        SearchHits hits = response.getHits();
        if (hits != null && hits.getHits().length > 0) {
            List<SkuEsModel> esModels = new ArrayList<>();
            for (SearchHit hit : hits) {
                SkuEsModel skuEsModel = JSON.parseObject(hit.getSourceAsString(), SkuEsModel.class);
                //TODO 设置高亮属性
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
            searchResult.setProduct(esModels);
        }
        //当前页码
        searchResult.setPageNum(searchParam.getPageNum());
//        //总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        Integer totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total / EsConstant.PRODUCT_PAGESIZE + 1;
        searchResult.setTotalPages(totalPages);
//        //页码遍历结果集(分页)
        List<Integer> pageNavs = new ArrayList<>();
        for (Integer i = 0; i < totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        //3. 查询结果涉及到的品牌
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            //获取品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            Aggregations subBrandAggs = bucket.getAggregations();
            //获取品牌名
            ParsedStringTerms brandNameAgg = subBrandAggs.get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            //获取品牌图片
            ParsedStringTerms brandImgAgg = subBrandAggs.get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo(brandId, brandName, brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        //4. 查询涉及到的所有分类
        ArrayList<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            //获取id
            Long catalogId = bucket.getKeyAsNumber().longValue();
            //获取分类名
            ParsedLongTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo(catalogId, catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

//        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
//         ParsedNested attr_agg =response.getAggregations().get("attr_agg");
//         ParsedLongTerms attr_id_agg =attr_agg.getAggregations().get("attr_id_agg");
//        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
//            long attrId = bucket.getKeyAsNumber().longValue();
//            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
//            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
//                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
//                return keyAsString;
//            }).collect(Collectors.toList());
//            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(attrId, attrName, attrValues);
//            attrVos.add(attrVo);
//        }
//        searchResult.setAttrs(attrVos);

        return searchResult;
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //keyword
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        //catalog filter
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //brandid
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //hasStock
        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        //priceRange
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
        if (StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            String[] prices = searchParam.getSkuPrice().split("_");
            if (prices.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(Integer.parseInt(prices[0]));
                } else {
                    rangeQueryBuilder.gte(Integer.parseInt(prices[0]));
                }
            } else {
                if (!StringUtils.isEmpty(prices[0])) {
                    rangeQueryBuilder.gte(Integer.parseInt(prices[0]));
                }
                rangeQueryBuilder.lte(Integer.parseInt(prices[1]));
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //attrs-nested
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            attrs.forEach(attr -> {
                BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
                String[] split = attr.split("_");
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                String[] split1 = split[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", split1));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });
        }

        //1. bool query构建完成
        sourceBuilder.query(boolQueryBuilder);

        //2. sort  eg:sort=saleCount_desc/asc
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String[] split = searchParam.getSort().split("_");
            SortOrder order = split[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(split[0], order);
        }
        //3 分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //4. 高亮highlight
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        //5. 聚合
        //品牌
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId");
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName"));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg"));
        sourceBuilder.aggregation(brandAgg);
        //分类
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId");
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName"));
        sourceBuilder.aggregation(catalogAgg);
//        //5.3 按照attrs聚合
//        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs", "attrs");
//        //按照attrId聚合
//        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
//        //按照attrId聚合之后再按照attrName和attrValue聚合
//        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"));
//        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"));
//        nestedAggregationBuilder.subAggregation(attrIdAgg);
//        sourceBuilder.aggregation(nestedAggregationBuilder);

        log.debug("构建的DSL语句 {}", sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}